#include "HomeWidget.h"
#include "ui_HomeWidget.h"
#include<QFile>
#include<QTableView>
#include<QStandardItemModel>
#include<QStringList>
#include<QDebug>
#include<QKeyEvent>
#include<QCheckBox>
#include<QTableView>
#include<QFileDialog>
#include"fileitem.h"
#include"HttpManage.h"
#include<QProgressBar>
#include<QMessageBox>
#include<QHBoxLayout>
#include<QDateTime>
#include<QFileInfo>
#include <QUrl>
#include<QThreadPool>
#include "fileitem.h"
#include "backup.hpp"
#include<QtConcurrent/QtConcurrent>
#include "httpdownload.h"
#include "Global.h"
HomeWidget::HomeWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::HomeWidget)
{
    ui->setupUi(this);

    //设置初始logo
    ui->LogoLabel->setPixmap(QPixmap(":/assets/cloud_gold.png").scaled((ui->LogoLabel->size()),Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
    //给当前对象安装事件筛选器
    this->installEventFilter(this);
    //设置qss样式
    QFile file(":/assets/HomeWidget.qss");
    if(file.open(QFile::OpenModeFlag::ReadOnly))
    {
        this->setStyleSheet(file.readAll());
        //后面记得添加file.close();
    }
    else
    {
        qDebug("read qss failed\n");
    }
    //设置所有单元格禁止被选中
    ui->ResourcesTableWidget->setSelectionMode(QAbstractItemView::NoSelection);
    //设置单元格禁止被修改
    ui->ResourcesTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //取消行号
    ui->ResourcesTableWidget->verticalHeader()->hide();

    //初始化左侧btform
    ui->homeBtform->seticon("://assets/home.png","主页",0);
    ui->transferBtform->seticon("://assets/transfer.png","传输",1);
    ui->stackedWidget->setCurrentIndex(0);
    initHttpHandlers();

    //信号连接
    connect(ui->homeBtform,&BtForm::btClick,this,&HomeWidget::onBtFormClick);
    connect(ui->transferBtform,&BtForm::btClick,this,&HomeWidget::onBtFormClick);

    connect(HttpManage::GetInstance().get(), &HttpManage::uploadRequested,
                HttpManage::GetInstance().get(), &HttpManage::handleUpload,
                Qt::QueuedConnection);
    //登录成功后发送一个http请求，显示所有用户上传文件,todo
    showFileList();
}

HomeWidget::~HomeWidget()
{
    delete ui;
}

void HomeWidget::keyPressEvent(QKeyEvent *ev)
{
    if(ev->key() == Qt::Key_F5)
    {
        qDebug()<<"刷新\n";
        QFile file("D:/qt_code/CloudBackup/assets/HomeWidget.qss");
        if(file.open(QFile::OpenModeFlag::ReadOnly))
        {
            this->setStyleSheet(file.readAll());
        }
    }
    return QWidget::keyPressEvent(ev);
}

void HomeWidget::initHttpHandlers()
{
    //文件上传回包逻辑
    _handles.insert(ReqId::UPLOAD_FILE,[this](QJsonObject jsonObj)
    {
        int error = jsonObj["code"].toInt();
        if(error != ErrorCode::SUCCESS)
        {
            QString errorMessage;
            switch (error)
            {
                case ErrorCode::ERR_NETWORK:
                     errorMessage = "客户端发送的请求不合法";
                     break;
                default:
                     errorMessage = QString("未知错误 (代码: %1)").arg(error);
            }
            QMessageBox::warning(this, "上传失败", errorMessage);
                return;
        }
        // 提示登录成功
        //成功上传一个就发出一个提示音，todo
        qDebug()<<"文件上传成功"<<'\n';
    });
}


void HomeWidget::on_MyFilePushButton_clicked()
{
    bool is_conceal = ui->listWidget->isVisible();
    if(is_conceal == true)
    {
        ui->listWidget->setVisible(false);
        ui->MyFilePushButton->setIcon(QIcon("://assets/unfold_unsel.png"));
    }
    else
    {
        ui->listWidget->setVisible(true);
        ui->MyFilePushButton->setIcon(QIcon("://assets/unfold_sel.png"));
    }
}
void autoUploadTask(QString backup_dir)
{
    QString appPath = QCoreApplication::applicationDirPath();
    Backup back(backup_dir,appPath+"/backup.dat");
    back.RunModule();
}
void HomeWidget::on_UploadPushButton_clicked()
{
    if(ui->autoBackupText->text() == "")
    {
        QString filePath = QFileDialog::getExistingDirectory(nullptr, "选择要自动备份的文件夹", "", QFileDialog::ShowDirsOnly);
        QString tempText = "当前自动备份文件夹为：";
        ui->autoBackupText->setText(tempText+filePath);
        //说明没有选过文件夹
        QtConcurrent::run([=]()
                          {
            autoUploadTask(filePath);
                          });
    }
    else
    {
        //选过了就不让更改了
        ui->UploadPushButton->setEnabled(false);
    }
}

void HomeWidget::onBtFormClick(int id)
{
    //清楚之前btform按钮的颜色背景
    QList<BtForm*> btFormList = this->findChildren<BtForm*>();
    for (auto btForm : btFormList)
    {
        if(btForm->getId() != id)
        {
            btForm->clearBackground();
        }
    }

    ui->stackedWidget->setCurrentIndex(id);
    qDebug()<<"切换页面："<<id<<'\n';
}

void HomeWidget::onCancelTask(FileItem *item)
{
    ui->transferList->removeItemWidget(item->getListItem());
}

void HomeWidget::showFileList()
{
    //先清理资源
    ui->fileList->clear();
    //发起http请求获取文件资源
    HttpManage::GetInstance()->showFileList(gate_url_prefix+"/list");
    connect(HttpManage::GetInstance().get(),&HttpManage::sig_file_list_received,this,[&](QVector<QJsonValue> fileList,ErrorCode error){
        if(error == ErrorCode::ERR_NETWORK)
            qDebug()<<"网络错误，获取文件列表失败\n";
        else if(error == ErrorCode::ERR_SERVER)
            qDebug()<<"服务器内部错误，获取文件列表失败\n";
        else if(error == ErrorCode::ERR_JSON)
            qDebug()<<"json 解析失败，无法获取文件列表\n";

        //qDebug()<<fileList<<'\n';
        for(auto& str : fileList)
        {
            QJsonObject jsonItem = str.toObject();
            QString filename = jsonItem["filename"].toString();
            quint64 fileSize = jsonItem["size"].toInteger();
            QString downloadUrl = jsonItem["download_url"].toString();
            FileListItem* item = new FileListItem(downloadUrl,ui->fileList);
            item->setFilename(filename);
            //后面处理，文件大小单位转换
            item->setFileSize(formatFileSizeQt(fileSize));
            item->setFiletype(getFileType(filename));
            ui->fileList->addItem(item);
        }
    });
}

QString HomeWidget::getFileType(const QString &filename)
{
    QFileInfo fileInfo(filename);
    QString suffix = fileInfo.suffix().toLower();

    // 类型映射表（支持扩展）
    static const QHash<QString, QString> typeMap = {
        // 图片类型
        {"png", "图片"}, {"jpg", "图片"}, {"jpeg", "图片"},
        {"gif", "动图"}, {"bmp", "位图"}, {"webp", "网页图片"},

        // 文档类型
        {"pdf", "PDF文档"}, {"doc", "Word文档"}, {"docx", "Word文档"},
        {"ppt", "PPT文档"}, {"pptx", "PPT文档"}, {"xls", "Excel文档"},
        {"xlsx", "Excel文档"}, {"txt", "文本文件"}, {"md", "Markdown文件"},

        // 音视频
        {"mp3", "音频"}, {"wav", "音频"}, {"mp4", "视频"},
        {"avi", "视频"}, {"mov", "视频"}, {"mkv", "高清视频"},

        // 压缩文件
        {"zip", "压缩包"}, {"rar", "压缩包"}, {"7z", "7-Zip压缩包"},
        {"tar", "TAR压缩包"}, {"gz", "GZIP压缩包"},

        // 可执行文件
        {"exe", "可执行程序"}, {"dll", "动态链接库"}, {"bat", "批处理脚本"}
    };

    // 特殊类型判断
    if (fileInfo.isDir()) return "目录";
    if (suffix.isEmpty()) return "其他文件";

    return typeMap.contains(suffix) ? typeMap[suffix] : QString("%1文件").arg(suffix.toUpper());
}

QString HomeWidget::formatFileSizeQt(quint64 bytes, int precision)
{
    QLocale locale(QLocale::English); // 设置为英文格式
    return locale.formattedDataSize(
        bytes,
        precision,
        QLocale::DataSizeTraditionalFormat // 使用1024进制
        );
}


void HomeWidget::on_DownloadPushButton_clicked()
{
    //选择下载文件保存的位置
    QString localPath = QFileDialog::getExistingDirectory(nullptr, "选择文件下载位置",qApp->applicationDirPath(),QFileDialog::ShowDirsOnly);
    if(localPath.isEmpty())
    {
        return;
    }
    QList<QListWidgetItem *> selectItemsList;
    ui->fileList->getSelectedItems(&selectItemsList);
    // 获取FileList内部的QListWidget
    QListWidget* fileListWidget = ui->fileList->getListWidget();
    // 遍历选中项
    foreach (QListWidgetItem* item, selectItemsList)
    {
        // 获取自定义控件（类型为 FileListItem）
         QWidget* widget = fileListWidget->itemWidget(item);
        if (widget == nullptr)
        {
            continue; // 如果没有关联控件，跳过该项
        }
        FileListItem* customItem = qobject_cast<FileListItem*>(widget);
        if (customItem == nullptr)
        {
            continue; // 如果类型转换失败，跳过该项
        }
        QString filename = customItem->getFilename();
        QString url = customItem->getUrl();
        QString localFileName = localPath+"/"+filename;
        qint64 fileSize = customItem->getFileSize();

        QListWidgetItem* listItem = new QListWidgetItem();
        ui->transferList->addItem(listItem);
        FileItem* fileWidget = new FileItem();
        fileWidget->setFileName(filename);
        fileWidget->setFileSize(fileSize);
        ui->transferList->setItemWidget(listItem,fileWidget);

        //创建传输任务
        HttpDownload* task = new HttpDownload(gate_url_prefix +url,localFileName);
        connect(task,&HttpDownload::downloadProgress,qApp,[=](qint64 bytesReceived,qint64 bytesTotal){
            // 进度、速率、时间。到这里一起更新
            fileWidget->updateProgress(bytesReceived,bytesTotal);

        },Qt::QueuedConnection);
        connect(task,&HttpDownload::finished,qApp,[=](){
            // 从传输列表中安全移除项
            int row = ui->transferList->row(listItem);
            QListWidgetItem* takenItem = ui->transferList->takeItem(row);

            // 释放内存
            delete takenItem;  // 删除列表项
            fileWidget->deleteLater();  // 安全删除关联的 FileItem
        },Qt::QueuedConnection);
        QThreadPool::globalInstance()->start(task);
    }
}


void HomeWidget::on_RefreshPushButton_clicked()
{
    showFileList();
}

